<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>微信简易聊天室</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <style type="text/css">
        @media screen and (min-width: 320px) and (max-width: 1156px) {
            .talk_con_mob {
                width: 600px;
                height: 500px;
                border: 1px solid #666;
                margin: 50px auto 0;
                background: #f9f9f9;
            }

            .talk_show_mob {
                width: 580px;
                height: 420px;
                border: 1px solid #666;
                background: #fff;
                margin: 10px auto 0;
                overflow: auto;
            }

            .talk_input_mob {
                width: 580px;
                margin: 10px auto 0;
            }

            .talk_word_mob {
                width: 420px;
                height: 26px;
                padding: 0px;
                float: left;
                margin-left: 10px;
                outline: none;
                text-indent: 10px;
            }
        }

        .talk_con {
            width: 600px;
            height: 500px;
            border: 1px solid #666;
            margin: 50px auto 0;
            background: #f9f9f9;
        }

        .talk_show {
            width: 780px;
            height: 720px;
            border: 1px solid #666;
            background: #fff;
            margin: 10px auto 0;
            overflow: auto;
        }

        .talk_input {
            width: 580px;
            margin: 10px auto 0;
        }

        .whotalk {
            width: 80px;
            height: 30px;
            float: left;
            outline: none;
        }

        .talk_word {
            width: 420px;
            height: 26px;
            padding: 0px;
            float: left;
            margin-left: 10px;
            outline: none;
            text-indent: 10px;
        }

        .talk_sub {
            width: 56px;
            height: 30px;
            float: right;
            margin-right: 10px;
        }

        .atalk {
            margin: 10px;
        }

        .atalk span {
            display: inline-block;
            background: #0181cc;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
        }

        .btalk {
            margin: 10px;
            text-align: right;
        }

        .btalk span {
            display: inline-block;
            background: #ef8201;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
        }

        .talk_con {
            width: 800px;
            height: 800px;
            margin: 20px auto 0;
        }

        .last_sender {
            display: inline-block;
            width: 150px;
            float: left;
            color: #ef8201;
            margin-top: 15px;
            text-align: center;
            cursor: pointer;
        }

        .auto_reply {
            display: inline-block;
            width: 150px;
            float: right;
            color: blue;
            margin-top: 15px;
            text-align: center;
            cursor: pointer;
        }

        .auto_reply.stop {
            color: red;
        }
    </style>
</head>
<body>
<div class="talk_con" id="talk_con_id">
    <div class="talk_show" id="words">
        <div class="atalk"><span id="asay" class="tips-opens"></span></div>
        <!-- div class="btalk"><span id="bsay">用户说：还没呢，你呢？</span></div -->
    </div>
    <div class="last_sender" id="lastSender"></div>
    <div class="auto_reply" id="autoreply"></div>
    <div class="talk_input" id="talk_input_id">
        <input type="text" class="talk_word" id="talkwords"/>
        <input type="button" value="发送" class="talk_sub" id="talksub"/>
    </div>
</div>


<script type="text/javascript">
	$(function(){		
		//开启自动回复
		startAutoReply()
	})

    /*--------------------------    微信socket消息    --------------------------*/

    //最后一个发送者
    let lastSender;
    let senderSet = new Set();
    const upgradingTips = '服务升级中,请稍后重试~~'
    const upgradeFinishedTips = '系统现已升级完毕~\n给您带来的不便敬请谅解。';

    var ws = new WebSocket('ws://39.104.84.85:5555');

    const HEART_BEAT = 5005;
    const RECV_TXT_MSG = 1;
    const RECV_PIC_MSG = 3;
    const USER_LIST = 5000;
    const GET_USER_LIST_SUCCSESS = 5001;
    const GET_USER_LIST_FAIL = 5002;
    const TXT_MSG = 555;
    const PIC_MSG = 500;
    const AT_MSG = 550;
    const CHATROOM_MEMBER = 5010;
    const CHATROOM_MEMBER_NICK = 5020;
    const PERSONAL_INFO = 6500;
    const DEBUG_SWITCH = 6000;
    const PERSONAL_DETAIL = 6550;
    const DESTROY_ALL = 9999;
    const NEW_FRIEND_REQUEST = 37;//微信好友请求消息1
    const AGREE_TO_FRIEND_REQUEST = 10000;//同意微信好友请求消息

    ws.onopen = function () {
        console.log("socket连接成功了...")
        $('.tips-opens').text("微信聊天室连接成功了~")
    };

    ws.onmessage = function (e) {
        const j = JSON.parse(e.data);
        const type = j.type;
        switch (type) {
            case CHATROOM_MEMBER_NICK:
            case PERSONAL_DETAIL:
            case AT_MSG:
            case DEBUG_SWITCH:
            case PERSONAL_INFO:
            case TXT_MSG:
            case PIC_MSG:
            case CHATROOM_MEMBER:
                console.log(j);
                break;
            case RECV_PIC_MSG:
            case RECV_TXT_MSG:
                console.log(j);
                let wxid = j.id1 || j.id2;
                if(wxid && wxid.includes("chatroom")) return;

                //收到消息
                showReceiveMessage(wxid, j.content)
                //组装自动回复消息
                if (window.autoReply) {
                    sendMessage(wxid, upgradingTips)
                }
                break;
            case HEART_BEAT:
            case USER_LIST:
            case GET_USER_LIST_SUCCSESS:
            case GET_USER_LIST_FAIL:
                console.log(j);
                break;
            case NEW_FRIEND_REQUEST:
            case AGREE_TO_FRIEND_REQUEST:
                console.log(j);
                break;
            default:
                break;
        }
    };

    ws.onerror = function (e) {
        console.log('error');
        $('.tips-opens').text("微信聊天室已断开连接~")
        alert('微信聊天室已断开连接~')
    };
    ws.onclose = function (e) {
        console.log('disconnected');
        $('.tips-opens').text("微信聊天室已断开连接~")
        alert('微信聊天室已断开连接~')
    };

    /*--------------------------    页面数据    --------------------------*/

    var $Words = $('#words');
    var $TalkWords = $('#talkwords');
    var $TalkSub = $('#talksub');
    var $autoReply = $('#autoreply');
    var $lastSender = $('#lastSender')

    //发送消息
    var sendMessage = function (sender, content) {
        var wxid = sender || lastSender;
        if (ws && content && wxid) {
            ws.send(JSON.stringify({
                id: Date.now().toString(),
                type: TXT_MSG,
                wxid,
                content,
                roomid:"null",
                nickname:"null",
                ext: 'null'
            }));
            $Words.html($Words.html() + '<div class="btalk"><span>接收者：' + wxid + '<br/>内容：' + content + '</span></div>');
        }
    }

    //收到消息
    var showReceiveMessage = function (sender, msg) {

        //设置当前发送者
        lastSender = sender;
        $lastSender.text(sender)
        //发送人列表
        senderSet.add(sender);

        msg && $Words.html($Words.html() + '<div class="atalk"><span>发送者：' + sender + '<br/>内 &nbsp 容：' + msg + '</span></div>');
        // 滑动到最底部
        $Words.scrollTop($Words[0].scrollHeight);
    }

    //点击发送
    $TalkSub.click(function () {
        // 消息为空时弹窗
        if (!$TalkWords.val()) {
            alert("消息不能为空");
            return;
        }

        //将之前的内容与要发的内容拼接好 提交
        sendMessage(null, $TalkWords.val())
    });

    //点击开启关闭自动回复
    $autoReply.click(function () {
        if ($autoReply.hasClass('stop')) {
            //已关闭 -> 开启
            startAutoReply();
        } else {
            //已开启 -> 关闭
            stopAutoReply();
        }
    })

    //开启自动回复
    var startAutoReply = function () {
        window.autoReply = true;
        $autoReply.text('自动回复已开启').removeClass('stop')
    }

    //关闭自动回复
    var stopAutoReply = function () {
        window.autoReply = false;
        $autoReply.text('自动回复已关闭').addClass('stop')
        alert('自动回复已关闭')
    }

    //构建样式
    var sUserAgent = navigator.userAgent;
    if (sUserAgent.indexOf('Android') > -1 || sUserAgent.indexOf('iPhone') > -1 || sUserAgent.indexOf('iPad') > -1 || sUserAgent.indexOf('iPod') > -1 || sUserAgent.indexOf('Symbian') > -1) {
        $('#talk_con_id').addClass('talk_con_mob')
        $('#words').addClass('talk_show_mob')
        $('#talk_input_id').addClass('talk_input_mob')
        $('#talkwords').addClass('talk_word_mob')
    } else {
        $('#talk_con_id').addClass('talk_con')
        $('#words').addClass('talk_show')
        $('#talk_input_id').addClass('talk_input')
        $('#talkwords').addClass('talk_word')
    }

    //退出前通知所有用户
    window.onbeforeunload = function (e) {
        if(senderSet && senderSet.size){
            for (let wxid of senderSet){
                sendMessage(wxid,upgradeFinishedTips)
            }
        }
    }
</script>
</body>
</html>